package com.stage.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * Created by Stage on 2017/3/10.
 */
public class ExtractInterface {
    private FileOperation fileOperation = new FileOperation();

    public void extractMethod(String firstObjectName, String secondObjectName) {
        try {
            Class<?> firstClazz = Class.forName(firstObjectName);
            Class<?> secondClazz = Class.forName(secondObjectName);
            Class<?> temp = Class.forName("com.stage.proxy.ExtractInterface");
            Method[] firstClazzMethods = firstClazz.getMethods();
            Method[] secondClazzMethods = secondClazz.getMethods();
            Method[] tempMethods = temp.getMethods();
            ArrayList<String> firstClazzMethodsList = getArrayList(firstClazzMethods);
            ArrayList<String> secondClazzMethodsList = getArrayList(secondClazzMethods);
            ArrayList<String> tempMethodsList = getArrayList(tempMethods);

            ArrayList<String> result = new ArrayList<>();
            result.clear();
            result.addAll(firstClazzMethodsList);
            result.removeAll(tempMethodsList);
            result.retainAll(secondClazzMethodsList);
            fileOperation.fileWriter(firstObjectName + secondObjectName + "Interface.java", "public interface " + firstObjectName + secondObjectName + "Interface");
            fileOperation.fileWriter(firstObjectName + secondObjectName + "Interface.java", "{");
            for (String method : result
                    ) {
                fileOperation.fileWriter(firstObjectName + secondObjectName + "Interface.java", "public " + method.toString());
            }
            fileOperation.fileWriter(firstObjectName + secondObjectName + "Interface.java", "}");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private ArrayList<String> getArrayList(Method[] methods) {
        ArrayList<String> result = new ArrayList<>();
        for (Method method : methods
                ) {
            StringBuffer parameters = new StringBuffer();
            Class<?>[] parameterTypes = method.getParameterTypes();
            int i = 0;
            for (Class<?> clas : parameterTypes) {
                String parameterName = clas.getName();
                parameters.append(parameterName + " arg" + i);
                i++;
            }
            result.add(method.getReturnType() + " " + method.getName() + " (" + parameters + ");");
        }
        return result;
    }
}
